﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TaggerApp.MSTagRefService;
using System.Configuration;
using TaggerApp.Authentication;

namespace TaggerApp.Admin.Pages.EditTagInfo
{
    public partial class Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //User myUser = (User)Session["user"];
            //if (myUser == null)
            //{
            //    Response.Redirect("~/Pages/Login");
            //}
            //else if (!myUser.Role.Equals("Admin"))
            //{
            //    Response.Redirect("~/Pages/Unauthorized/Unauthorized.aspx");
            //}

            Global title = new Global();
            title.GetTitleFromDB();
            Page.Title = "Edit Product Details - " + title.appName;
            sucessMessage.Visible = false;
        }
        public string oldName, newName, tagGUID, appName;

        protected void DetailsViewProduct_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            Label currentName = DetailsViewProduct.FindControl("lblName") as Label;
            TextBox txtBoxName = DetailsViewProduct.FindControl("txtBoxNameEdit") as TextBox;
            newName = txtBoxName.Text;
            oldName = currentName.Text;
            UpdateTag();
            sucessMessage.Visible = true;            
        }

        protected void DetailsViewProduct_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            TextBox lblGUID = DetailsViewProduct.FindControl("txtBoxGUID") as TextBox;
            tagGUID = lblGUID.Text;
        }

        private void UpdateTag()
        {
                MIBPContractClient OMIBPClient = new MIBPContractClient();
                UserCredential oCredential = new UserCredential();
                oCredential.AccessToken = ConfigurationManager.AppSettings["MSTagAPIKey"];
                URITag uriTag = new URITag();
                uriTag.Title = newName;
                uriTag.MedFiUrl = "http://mstaggerdev.azurewebsites.net/Devices.aspx?id=" + tagGUID;
                uriTag.UTCStartDate = DateTime.Now;
                OMIBPClient.UpdateTag(oCredential, "Main", oldName, uriTag);
        }
    }
}